package main

import (
	"encoding/json"
	"github.com/jinzhu/gorm"
	"net/http"
)

type JiaMeng struct {
	gorm.Model
	Name    string
	Contact string
	City    string
}

func (this *JiaMeng) TableName() string {
	return "jiameng"
}

//订阅设备
func HandleJiameng(w http.ResponseWriter, r *http.Request) {
	v := r.URL.Query()
	name := v.Get("name")
	if name == "" {
		JsonResponse(w, 404, "姓名不能为空！", map[string]interface{}{})
		return
	}
	city := v.Get("city")
	if city == "" {
		JsonResponse(w, 404, "城市不能为空！", map[string]interface{}{})
		return
	}
	contact := v.Get("contact")
	if contact == "" {
		JsonResponse(w, 404, "联系方式不能为空！", map[string]interface{}{})
		return
	}
	jm := &JiaMeng{}
	jm.Name = name
	jm.City = city
	jm.Contact = contact
	db := GetDB()
	err := db.Table(jm.TableName()).Create(jm).Error
	if err != nil {
		JsonResponse(w, 400, err.Error(), map[string]interface{}{})
		return
	}
	JsonResponse(w, 200, "success", map[string]interface{}{})
	return
}

//订阅设备
func HandleMobileSend(w http.ResponseWriter, r *http.Request) {
	v := r.URL.Query()
	mobile := v.Get("mobile")
	if mobile == "" {
		JsonResponse(w, 404, "手机号不能为空！", map[string]interface{}{})
		return
	}
	code := v.Get("code")
	if code == "" {
		JsonResponse(w, 404, "验证码不能为空！", map[string]interface{}{})
		return
	}
	err := SendAliSms(mobile, code)
	if err != nil {
		JsonResponse(w, 400, err.Error(), map[string]interface{}{})
		return
	}
	JsonResponse(w, 200, "success", map[string]interface{}{})
}

type JsonResult struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"'data'"`
}

func JsonResponse(w http.ResponseWriter, code int, msg string, data interface{}) {
	w.Header().Set("Content-Type", "application/json")
	w.Header().Set("Content-Type", "application/json; charset=UTF-8")
	w.Header().Set("Access-Control-Allow-Headers", "X-Requested-With,Accept, Content-Type,"+
		" Content-Length, Accept-Encoding,Deviceid,type, X-CSRF-Token,Authorization,Sign,app-mode")
	w.Header().Set("Access-Control-Allow-Origin", "*")
	w.Header().Set("Server", "xidian")
	w.Header().Set("Access-Control-Request-Method", "GET,HEAD,PUT,PATCH,POST,DELETE")
	res := JsonResult{
		Code: code,
		Msg:  msg,
		Data: data,
	}
	_ = json.NewEncoder(w).Encode(res)
}
